﻿/* $RCSFile: AdminUsers.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/AdminUsers/AdminUsers.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:18  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:44  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.IO;
using System.ComponentModel;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Authentication;

using AddonNice.CRMWrapper;

using Telerik.Web.UI;
using Telerik.Web.UI.Upload;

using Trace2    =   System.Diagnostics.Trace;
using Path2     =   AddonNice.Settings.Path;

namespace AddonNice.PageModules.AdminUsers
{
 	#region Local TraceSwitch 
	public class AdminUsersTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("AdminUsersTrace","Special Trace Switch for AdmiUsers");
	}
	#endregion Local TraceSwitch 

    /// <summary>
    /// Initializer class for AdminUsers 
    /// </summary>
    public class AdminUsersSI : PortalCRMModuleControlSI
    {
        public AdminUsersSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]AdminUsersSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]AdminUsersSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]AdminUsersSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);
        }
    }

    public partial class AdminUsers : PortalCRMModuleControl
    {
        #region General implementation

        public override bool AdminModule
        {
            get
            {
                return true;
            }
        }


        public override Guid GuidID
        {
            get
            {
                return new Guid("{7601EFD3-C86F-4e39-B44A-3A46CD9325F8}");
            }
        }
        #endregion General implementation


        Guid firstOwner                         =   Guid.Empty;
        ArrayList _PotentialOwners              =   null;
        ArrayList PotentialOwners
        {
            get
            {
                if ( _PotentialOwners == null )
                {
                    _PotentialOwners               =   Wrapper.Util.PotentialOwners(ref firstOwner,false);
                }
                return _PotentialOwners;
            }

        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers Page_Load BEG IsPostBack: {0}.",IsPostBack),ModuleTraceSwitch.Sw.Info);
            if ( !IsPostBack )
            {
                // if user authenticated and admin we go directly to users tab
                MembershipUser muser                    =   Membership.GetUser();
                if ( muser != null )
                {
                    AddonNiceMembershipUser usr         =   (AddonNiceMembershipUser)muser;
                    if (usr.IsAdmin(Wrapper))
                    {
                        RqV1.Enabled                        =   false;
                        RadTabStrip1.Tabs[0].Enabled        =   false;
                        RadMultiPage1.PageViews[0].Selected =   false;
                        RadTabStrip1.Tabs[1].Enabled        =   true;
                        RadTabStrip1.Tabs[1].Selected       =   true;
                        RadMultiPage1.PageViews[1].Selected =   true;
                    }
                }
            }
        }

        void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers RadGrid1_NeedDataSource BEG RebindReason: {0}.",e.RebindReason),ModuleTraceSwitch.Sw.Info);
            MembershipUserCollection   tbUsers  =   null;
            try
            {
                tbUsers                         =   Membership.GetAllUsers();
                // check to see if current admin user is created in Membership
                bool created                    =   false;
                foreach (AddonNiceMembershipUser usr in tbUsers)
                {
                    if ( usr.CrmImpersonateId == Wrapper.adminUserId )
                    {
                        ADNDynSystemUser wus    =   usr.GetImpersonateUser(Wrapper);
                        if (wus.domainname.ToLower(CultureInfo.InvariantCulture) == string.Format("{0}\\{1}",usr.CrmImpersonateDomain,usr.CrmImpersonateLogin).ToLower(CultureInfo.InvariantCulture) )
                        {
                            created             =   true;
                            break;
                        }
                    }
                }
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers RadGrid1_NeedDataSource Admin user created: {0}.",created),ModuleTraceSwitch.Sw.Info);
                // Enable Create Admin Button
                if (!created)
                {
                    BtnCreate.Visible           =   true;
                }
                else BtnCreate.Visible          =   false;

                RadGrid1.DataSource             =   tbUsers;
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AdminUsers RadGrid1_NeedDataSource ex: {0}.",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]AdminUsers RadGrid1_NeedDataSource END.",ModuleTraceSwitch.Sw.Info);
        }
        
        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridEditableItem )
            {
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers RadGrid1_ItemDataBound BEG Item: {0}, Type: {1}, IsInEditMode: {2}",
                        e.Item,e.Item.ItemType,e.Item.IsInEditMode),ModuleTraceSwitch.Sw.Info);
                GridEditableItem item               =   (GridEditableItem)e.Item;
                if ( item.IsInEditMode )
                {
                    bool binded                     =   false;
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers RadGrid1_ItemDataBound DataItem: {0}",e.Item.DataItem.GetType()),ModuleTraceSwitch.Sw.Info);
                    if ( !(e.Item.DataItem is AddonNiceMembershipUser) )
                        return;
                    AddonNiceMembershipUser rw      =   null;
                    if ( !item.OwnerTableView.IsItemInserted )
                        rw                          =   (AddonNiceMembershipUser)e.Item.DataItem;
                    try
                    {  
                        GridEditManager editMan     =   item.EditManager;

                        GridDropDownListColumnEditor editor =   (GridDropDownListColumnEditor)editMan.GetColumnEditor( "CrmImpersonateId" );
                        //in case you have RadComboBox editor for the GridDropDownColumn (this is the default editor),         
                        //you will need to use ComboBoxControl below instead of DropDownListControl
                        //Then you can modify the list control as per your custom conventions
                        editor.DataSource           =   PotentialOwners;
                        editor.DataBind();
                        if (rw != null)
                        {
                            RadComboBoxItem it      =   editor.ComboBoxControl.Items.FindItemByValue(rw.CrmImpersonateId.ToString());
                            if (it != null)
                                it.Selected         =   true;
                        }
                        binded                      =   true;
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers RadGrid1_ItemDataBound AttributeType Count: {0}",editor.ComboBoxControl.Items.Count),ModuleTraceSwitch.Sw.Info);
                    }
                    catch(Exception ex)
                    { 
                        if (ModuleTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AdminUsers RadGrid1_ItemDataBound ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                    }
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers RadGrid1_ItemDataBound END binded: {0}",binded),ModuleTraceSwitch.Sw.Info);
                }
                else
                {
                    if ( e.Item.ItemType != GridItemType.Item && 
                        e.Item.ItemType != GridItemType.AlternatingItem )
                        return;
                    if ( !(e.Item.DataItem is AddonNiceMembershipUser) )
                        return;
                    AddonNiceMembershipUser rw  =   (AddonNiceMembershipUser)e.Item.DataItem;
                    Guid ival                   =   rw.CrmImpersonateId;
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers RadGrid1_ItemDataBound CrmImpersonateId: {0}",ival),ModuleTraceSwitch.Sw.Info);
                    item["CrmImpersonateId"].Text  =   rw.CrmImpersonateLogin;
                }
                
            }
        }

        protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers RadGrid1_UpdateCommand BEG e.Item : {0}",e.Item),ModuleTraceSwitch.Sw.Info);
            GridEditableItem editedItem     =   e.Item as GridEditableItem;
            string strReq                   =   editedItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["UserName"].ToString();
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers RadGrid1_UpdateCommand UserName: {0}",strReq),ModuleTraceSwitch.Sw.Info);

            Hashtable newValues         =   new Hashtable();
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);

            try
            {
                string newGuid  =   newValues["CrmImpersonateId"].ToString();
                string newPwd   =   newValues["NewPwd"].ToString();
                if ( newGuid != null )
                {
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers RadGrid1_UpdateCommand updating userName: {0}, Value: {1}", strReq, newGuid), ModuleTraceSwitch.Sw.Info);
                    AddonNiceMembershipUser user =  (AddonNiceMembershipUser)Membership.GetUser(strReq);
                    if ( user != null )
                    {
                        // we check this credential and update if Ok
                        if ( user.SetImpersonateSystemuser(Wrapper, new Guid(newGuid), newPwd) )
                        {
                            Membership.UpdateUser(user);
                            RadGrid1.Controls.Add(new LiteralControl(LocalizeHelper.Localize("ADMINUSERS_USER_UPDATED","User updated.")));
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers RadGrid1_UpdateCommand updated Ok userName: {0}.", strReq), ModuleTraceSwitch.Sw.Info);
                            return;
                        }
                    }
                }
                RadGrid1.Controls.Add(new LiteralControl(LocalizeHelper.Localize("ADMINUSERS_USER_NOT_UPDATED","Unable to update User. please check entered password")));
                e.Canceled = true;
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AdminUsers RadGrid1_UpdateCommand ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }

        /// <summary>
        /// Create the Admin user if not there
        /// </summary>
        void BtnCreate_Click(object sender, ImageClickEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]AdminUsers BtnCreate_Click  BEG ",ModuleTraceSwitch.Sw.Info);
            try
            {
                AddonNiceMembershipProvider prov    =  (AddonNiceMembershipProvider)Membership.Provider;
                bool ok                             =   prov.TestAdmin(true);
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AdminUsers BtnCreate_Click END ok: {0}", ok), ModuleTraceSwitch.Sw.Info);
                if (ok )
                    RadGrid1.Rebind();
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AdminUsers BtnCreate_Click ex: {0}", ex), ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }

        void BtnNext_Click(object sender, ImageClickEventArgs e)
        {
            int idx                     =   RadTabStrip1.SelectedIndex;
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers BtnNext_Click  BEG TabIndex: {0}.",idx),ModuleTraceSwitch.Sw.Info);
            // Check that entered user is an Admin in Crm
            string user                 =   TbAdminLogin.Text.Trim();
            ADNDynSystemUser sysUser    =   Wrapper.Util.FindSystemUserByDomainName(user);
            if ( (sysUser != null) && sysUser.IsUserInRoles(Config.CRMAdminRole) )
            {
			    RadTab Tab              =   RadTabStrip1.Tabs[idx+1];
			    Tab.Enabled             =   true;
			    Tab.Selected            =   true;
                RadPageView PageView    =   RadMultiPage1.PageViews[idx+1];
			    PageView.Selected       =   true;
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers BtnNext_Click END New Tab Index: {0}.",Tab.Index),ModuleTraceSwitch.Sw.Info);
            }
		}

        #region Std Control override
 
        /// <summary>
        /// Triggered from Page.OnPreInit
        /// We must set the Add button before buttons are initialized by base method
        public override void Page_PreInit(object sender, EventArgs e)
        {
            // Add a link for the edit page
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AdminUsers Page_PreInit BEG IsPosBack: {0}", IsPostBack),ModuleTraceSwitch.Sw.Info);
            //AddUrl                  =   Config.ModulesPath + "/Packages/AddPackage.aspx";
            base.Page_PreInit(sender, e);
            string strcult      =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            BtnNext.SkinID      =   "setupnext_" + strcult;
            BtnCreate.SkinID    =   "AddAdministrator_"+strcult;
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]AdminUsers Page_PreInit END.",ModuleTraceSwitch.Sw.Info);
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }
        

        private void InitializeComponent()
        {
            Load                        +=  new EventHandler(Page_Load);
            RadGrid1.NeedDataSource     +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.UpdateCommand      +=  new GridCommandEventHandler(RadGrid1_UpdateCommand);
            RadGrid1.ItemDataBound      +=  new GridItemEventHandler(RadGrid1_ItemDataBound);
            BtnNext.Click               +=  new ImageClickEventHandler(BtnNext_Click);
            BtnCreate.Click             +=  new ImageClickEventHandler(BtnCreate_Click);
       }

      #endregion Std Control override
    }
}